<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller\m1;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Middleware\Manager\AuthMiddleware;
use Hyperf\Di\Annotation\Inject;
use App\Controller\AbstractController;
use Hyperf\DbConnection\Db;
use App\Constants\ReturnCode;
use Qbhy\HyperfAuth\Annotation\Auth;
use Qbhy\HyperfAuth\AuthManager;
use App\Helper\Common;
use Throwable;

#[AutoController]
#[Middleware(AuthMiddleware::class)]
class HomeController extends AbstractController
{
    #[Inject]
    protected AuthManager $auth;
    /**
     * 修改密码
     *
     * @return void
     */
    public function modpwd(){
        $old_pwd = $this->request->input('old_pwd');
        $new_pwd = $this->request->input('new_pwd');
        if(empty($old_pwd)){
            return $this->fmt_response(ReturnCode::para_miss,'旧密码不能为空');
        }
        if(empty($new_pwd)){
            return $this->fmt_response(ReturnCode::para_miss,'新密码不能为空');
        }
        $token = $this->request->input('token');
        $id = $this->auth->id($token);
        //判断旧密码是否正确
        $flag = Db::table('manager')->select('id')->where(['id'=>$id,'password'=>md5($old_pwd)])->exists();
        if(!$flag){
            return $this->fmt_response(ReturnCode::para_error,'旧密码不正确');
        }
        //开始更新数据
        Db::table('manager')->where('id', $id)->update(['password' => md5($new_pwd)]);
        //返回操作结果
        return $this->fmt_response(ReturnCode::deal_succ,'操作成功',true);
    }
    /**
     * 管理员用户列表
     *
     * @return void
     */
    public function mlist(){
        $username = $this->request->input('username');
        $currentPage = (int)$this->request->input('currentPage', 1);
        $pageSize = (int)$this->request->input('pageSize', 15);
        $where = [['is_del', '=', 0]];
        if (!empty($username)) {
            $where[] = ['username', '=', trim($username)];
        }
        $offset = ($currentPage - 1) * $pageSize;
        $fields = ['id', 'group_id', 'username', 'status', 'created_at','updated_at'];
        $model = Db::table('manager')->select($fields)->where($where);
        $total = $model->count();
        $list = $model->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($pageSize)
            ->get()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$value) {
                $value['group_name'] = $this->getGroupName($value['group_id']);
                $value['created_at'] = date("Y-m-d H:i:s",$value['created_at']);
                $value['updated_at'] = date("Y-m-d H:i:s",$value['updated_at']);
                unset($value['group_id']);
            }
        }
        $ret = [
            'total'=> $total,
            'list'=> $list,
        ];    
        return $this->fmt_response(ReturnCode::deal_succ,'操作成功',$ret);   
    }
    /**
     * 管理用户详情
     *
     * @return void
     */
    public function mdetail(){
        $id = (int)$this->request->input('id');
        if(!$id){
            return $this->fmt_response(ReturnCode::para_miss,'ID不能为空');
        }
        $row = Db::table('manager')->select(['id','group_id','username','extend_permission','status'])->where('id',$id)->first();
        return $this->fmt_response(ReturnCode::deal_succ,'获取成功',$row);
    }
    /**
     * 添加/编辑管理员用户
     *
     * @return void
     */
    public function addmb(){
        $id = (int)$this->request->input('id',0);
        $username = $this->request->input('username');
        $password = $this->request->input('password');
        $group_id = $this->request->input('group_id');
        $status = $this->request->input('status');
        $remark = $this->request->input('remark');
        if(empty($username)){
            return $this->fmt_response(ReturnCode::para_miss,'账号不能为空');
        }
        //判断账号是否存在
        $flag = Db::table('manager')->where([['username','=', $username], ['id','<>', $id], ['is_del','=', 0]])->exists();
        if($flag){
            return $this->fmt_response(ReturnCode::para_error,'账号已存在');
        }
        if(strlen($password)<6){
            return $this->fmt_response(ReturnCode::para_error,'密码不能小于6位');
        }
        $where = [
            'id'=>$id,
        ];
        $data = [
            'username'=>$username,
            'password'=>md5($password),
            'group_id'=>$group_id,
            'status'=>$status,
            'remark'=>$remark,
            'updated_at'=>time()
        ];
        if(empty($id)){
            $data['created_at'] = time();
        }
        $ret = Db::table('manager')->updateOrInsert($where,$data);
        if($ret){
            return $this->fmt_response(ReturnCode::deal_succ,'操作成功',$ret);
        }else{
            return $this->fmt_response(ReturnCode::deal_false,'操作失败');
        }
    }
    /**
     * 删除管理员
     *
     * @return void
     */
    public function delmb(){
        $id = (int)$this->request->input('id',0);
        $ret = Db::table('manager')->where('id', $id)->update(['is_del' => 1]);
        if($ret){
            return $this->fmt_response(ReturnCode::deal_succ,'操作成功',$ret);
        }else{
            return $this->fmt_response(ReturnCode::deal_false,'操作失败');
        }
    }
    /**
     * 编辑管理员扩展权限
     *
     * @return void
     */
    public function extrpurv(){
        $id = (int)$this->request->input('id',0);
        $extend_permission = $this->request->input('extend_permission','');
        //开始更新数据
        $ret = Db::table('manager')->where('id', $id)->update(['extend_permission' => $extend_permission]);
        if($ret){
            return $this->fmt_response(ReturnCode::deal_succ,'操作成功',$ret);
        }else{
            return $this->fmt_response(ReturnCode::deal_false,'操作失败');
        }
    }
    /**
     * 权限组列表
     *
     * @return void
     */
    public function grouplist(){
        $currentPage = (int) $this->request->input('currentPage', 1);
        $pageSize = (int) $this->request->input('pageSize', 15);
        $where = [['is_del', '=', 0]];
        $offset = ($currentPage - 1) * $pageSize;
        $fields = ['id', 'group_name', 'notes', 'created_at', 'updated_at'];
        $model = Db::table('permission_group')->select($fields)->where($where);
        $total = $model->count();
        $list = $model->orderBy('id', 'desc')
            ->offset($offset)
            ->limit($pageSize)
            ->get()
            ->toArray();
        if (!empty($list)) {
            foreach ($list as &$value) {
                $value['created_at'] = date("Y-m-d H:i:s", $value['created_at']);
                $value['updated_at'] = date("Y-m-d H:i:s", $value['updated_at']);
            }
        }
        $ret = [
            'total' => $total,
            'list' => $list,
        ];
        return $this->fmt_response(ReturnCode::deal_succ, '操作成功', $ret);
    }
    /**
     * 添加/删除 权限组
     *
     * @return void
     */
    public function addgroup(){
        $id = (int)$this->request->input('id',0);
        $group_name = $this->request->input('group_name');
        $permission = $this->request->input('permission');
        $notes = $this->request->input('notes');
        if(empty($group_name)){
            return $this->fmt_response(ReturnCode::para_miss,'权限组名不能为空');
        }
        //判断账号是否存在
        $flag = Db::table('permission_group')->where([['group_name','=', $group_name], ['id','<>', $id], ['is_del','=', 0]])->exists();
        if($flag){
            return $this->fmt_response(ReturnCode::para_error,'权限组名已存在');
        }
        $where = [
            'id'=>$id,
        ];
        $data = [
            'group_name'=>$group_name,
            'permission'=>$permission,
            'notes'=>$notes,
            'updated_at'=>time()
        ];
        if(empty($id)){
            $data['created_at'] = time();
            $data['addip'] = Common::getUserIp();
        }
        $ret = Db::table('permission_group')->updateOrInsert($where,$data);
        if($ret){
            return $this->fmt_response(ReturnCode::deal_succ,'操作成功',$ret);
        }else{
            return $this->fmt_response(ReturnCode::deal_false,'操作失败');
        }
    }
    /**
     * 删除权限组
     *
     * @return void
     */
    public function delgroup(){
        $id = (int)$this->request->input('id',0);
        $ret = Db::table('permission_group')->where('id', $id)->update(['is_del' => 1]);
        if($ret){
            return $this->fmt_response(ReturnCode::deal_succ,'操作成功',$ret);
        }else{
            return $this->fmt_response(ReturnCode::deal_false,'操作失败');
        }
    }
     /**
     * 管理员组id-名_tree
     *
     * @return void
     */
    public function gnametree(){
        $list = Db::table('permission_group')->select(['id','group_name'])->where('is_del',0)->get();
        return $this->fmt_response(ReturnCode::deal_succ,'获取成功',$list);
    }
    /**
     * 权限-tree
     *
     * @return void
     */
    public function purvtree(){
        $list = Db::table('permission')->select(['id','function_code','function_name','permission_name','path_info'])
                ->where('is_del',0)
                ->orderBy('function_code', 'asc')
                ->orderBy('sort', 'desc')
                ->get();
        return $this->fmt_response(ReturnCode::deal_succ,'获取成功',$list);
    }
    /**
     * 获取用户组名称
     *
     * @param integer $id
     * @return void
     */
    private function getGroupName($id = 0){
        $row = Db::table('permission_group')->select('group_name')->where('id',$id)->first();
        if(!empty($row)){
            return $row['group_name'];
        }else{
            return '';
        }
    }
    /**
     *
     * 权限组详情
     */
    public function gdetail()
    {
        $id = $this->request->input('id');
        $detail = Db::table('permission_group')->where(['id' => $id])->first();
        if (empty($detail)) {
            return $this->fmt_response(ReturnCode::deal_false, '获取失败');
        }
        return $this->fmt_response(ReturnCode::deal_succ, '获取成功', $detail);
    }
    
}